package com.sophimp.jumphack;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Random;

/**
 * Created by chenliang on 2018/1/1.
 */
public class Hack {


//    static final String ADB_PATH = "/Users/chenliang/Library/Android/sdk/platform-tools/adb";
    static final String ADB_PATH = "D:\\Android\\Sdk\\platform-tools\\adb.exe";

    /**
     * 弹跳系数，现在已经会自动适应各种屏幕，请不要修改。
     */
//    static final double JUMP_RATIO = 1.390f;
    static final double JUMP_RATIO = 2f;

    private static Random RANDOM = new Random();

    public static void main(String... strings) {
        String root = Hack.class.getResource("/").getPath();
        System.out.println("root: " + root);
        File srcDir = new File(root, "img/input");
        File desDir = new File(root, "img/output");
        srcDir.mkdirs();
        System.out.println("srcDir: " + srcDir.getAbsolutePath());
        MyPosFinder myPosFinder = new MyPosFinder();
        NextCenterFinder nextCenterFinder = new NextCenterFinder();
//        WhitePointFinder whitePointFinder = new WhitePointFinder();
        int total = 0;
        int centerHit = 0;
        double jumpRatio = 0;
        long startTime;
        for (int i = 0; i < 9000; i++) {
            try {
                startTime = System.currentTimeMillis();
                total++;
                File file = new File(srcDir, i + ".png");
                if (file.exists()) {
                    file.deleteOnExit();
                }
                Process process = Runtime.getRuntime().exec(ADB_PATH + " shell /system/bin/screencap -p /sdcard/screenshot.png");
                process.waitFor();
                process = Runtime.getRuntime().exec(ADB_PATH + " pull /sdcard/screenshot.png " + file.getAbsolutePath());
                process.waitFor();

                System.out.println("screenshot, file: " + file.getAbsolutePath());
                BufferedImage img = ImgLoader.load(file.getAbsolutePath());
                if (jumpRatio == 0) {
                    jumpRatio = JUMP_RATIO * 1080 / img.getWidth();
                }
                int[] myPos;
                if (i % 2 == 0){
                    // 在左边
                    myPos = myPosFinder.findLeft(img);
                }else {
                    myPos = myPosFinder.findRight(img);
                }
                if (myPos != null) {
                    System.out.println("find myPos, succ, (" + myPos[0] + ", " + myPos[1] + ")");
                    int[] nextCenter;
                    if (i % 2 == 0){
                        nextCenter = nextCenterFinder.findRight(img, myPos);
                    }else {
                        nextCenter = nextCenterFinder.findLeft(img, myPos);
                    }
                    if (nextCenter == null || nextCenter[0] == 0) {
                        System.err.println("find nextCenter, fail");
                        break;
                    } else {
                        int centerX = nextCenter[0], centerY = nextCenter[1];
                        System.out.println("find nextCenter, succ, (" + centerX + ", " + centerY + ") step: " + i + " cost time: " + (System.currentTimeMillis() - startTime));

                        if (nextCenter[0] < Constant.MIN_X || nextCenter[0] > Constant.MAX_X || nextCenter[1] < Constant.MIN_Y || nextCenter[1] > Constant.MAX_Y) {
                            // 非法坐标， 退出来
                            System.out.println("find nextCenter, invalid, (" + centerX + ", " + centerY + ")");
                            throw new RuntimeException("invalid target");
                        }

                        Graphics graphics = img.getGraphics();
//                        graphics.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);
                        // 识别的人物位置
                        graphics.setColor(Color.RED);
                        graphics.fillRect(myPos[0] - 5, myPos[1] - 5, 10, 10);

                        // 下一跳位置
                        graphics.setColor(Color.BLUE);
                        graphics.fillRect(nextCenter[0] - 5, nextCenter[1] - 5, 10, 10);

                        File desFile = new File(desDir, file.getName());
                        if (!desFile.exists()) {
                            desFile.mkdirs();
                            desFile.createNewFile();
                        }
                        ImageIO.write(img, "png", desFile);

                        // 模拟跳跃动作
                        int distance = (int) (Math.sqrt((centerX - myPos[0]) * (centerX - myPos[0]) + (centerY - myPos[1]) * (centerY - myPos[1])) * jumpRatio);
                        System.out.println("distance: " + distance);
                        int pressX = 400 + RANDOM.nextInt(100);
                        int pressY = 500 + RANDOM.nextInt(100);
                        String adbCommand = ADB_PATH + String.format(" shell input swipe %d %d %d %d %d", pressX, pressY, pressX, pressY, distance);
                        System.out.println(adbCommand);
                        Runtime.getRuntime().exec(adbCommand);
                    }
                } else {
                    System.err.println("find myPos, fail");
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
            try {
                // sleep 随机时间，防止上传不了成绩
                Thread.sleep(3000 + RANDOM.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        System.out.println("centerHit: " + centerHit + ", total: " + total);
    }

}
